package a08_回溯算法;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a09_分割回文串复习0
 * </p>
 *
 * @author flyduck
 * @since 2025/1/15
 */
public class a09_分割回文串复习0 {
    public static void main(String[] args) {
        a09_分割回文串复习0 test = new a09_分割回文串复习0();
        List<List<String>> aab = test.partition("aab");
        System.out.println(aab);
    }
    public List<List<String>> partition(String s) {
        List<List<String>> result = new ArrayList<>();
        LinkedList<String> path = new LinkedList<>();
        char[] chars = s.toCharArray();
        traversal(result, path, chars, 0);
        return result;
    }

    //splitIdx从
    private void traversal(List<List<String>> result,
                           LinkedList<String> path,
                           char[] chars,
                           int splitStartIdx){
        if(splitStartIdx > chars.length - 1){
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = splitStartIdx; i < chars.length; i++) {
            if (!isValid(chars, splitStartIdx, i)) {
                continue;
            }
            path.add(splitArray(chars, splitStartIdx, i));
            traversal(result, path, chars, i + 1);
            path.removeLast();
        }
    }

    private String splitArray(char[] chars,int leftIdx,int rightIdx){
        char[] result = new char[rightIdx - leftIdx + 1];
        int idx = 0;
        while (leftIdx <= rightIdx) {
            result[idx] = chars[leftIdx];
            idx++;
            leftIdx++;
        }
        return new String(result);
    }

    private boolean isValid(char[] chars,int leftIdx,int rightIdx){
        while (leftIdx < rightIdx) {
            if(chars[leftIdx] != chars[rightIdx]){
                return false;
            }
            leftIdx++;
            rightIdx--;
        }
        return true;
    }
}
